package com.sky.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.sky.domain.Book;
import com.sky.exception.BookException;
import com.sky.service.BookService;
import com.sky.utils.UploadUtils;

public class AddBookServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取请求参数
		Map<String, String> map = UploadUtils.HandleFormByUpload(request, getServletContext());
		
		Book book=new Book();
		try {
			BeanUtils.populate(book, map);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		book.setId(UUID.randomUUID().toString());
		System.out.println("======"+book.toString());
		//2.处理业务逻辑
		 BookService bookService =new BookService();
		 try {
			bookService.AddBook(book);
			//表示图书添加成功
			//待定
			request.getRequestDispatcher("queryBookServlet").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//表示图书添加失败
			request.setAttribute("error_book_msg", e.getMessage());
			request.setAttribute("book", book);
			request.getRequestDispatcher("product/add.jsp").forward(request, response);
		} catch (BookException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//表示图书添加失败
			request.setAttribute("error_book_msg", e.getMessage());
			request.setAttribute("book", book);
			request.getRequestDispatcher("product/add.jsp").forward(request, response);
		}
		//3.分发转向
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	

}
